using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

/// <summary>
///searchClass 的摘要说明
/// </summary>
public class searchClass
{
	public searchClass()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}

    /// 这就是你要的函数
        /// </summary>
        /// <param name="sourceXML">xml源码</param>
        /// <param name="keyword">关键字</param>
        /// <param name="priority">排序，必须区分大小写，在xml中包含，不能随便乱输入</param>
        /// <returns></returns>
        public static string getXMLByKeyword(string sourceXML, string keyword, string[] priority)
        {

            System.Xml.Linq.XDocument xd = System.Xml.Linq.XDocument.Load(new System.IO.StringReader(sourceXML));


            string[] TYPES = priority;
            string KEY = keyword;


            IEnumerable<System.Xml.Linq.XElement> els2=null;
            foreach (var TYPE in TYPES)
            {

                var els2a = MoreRow(TYPE.Trim(), KEY, xd);//排序有很多行，所以这个是获取某一排序关键Key，然后获取。
                if (els2 == null)
                {
                    els2 = els2a;
                }
                else
                {
                    els2 = els2.Union(els2a);//合并每一行的数据到一起，每一个row。
                }
            }



            System.Xml.Linq.XDocument xd2 = System.Xml.Linq.XDocument.Load(new System.IO.StringReader(sourceXML));
            xd2.Root.Element("Mrows").RemoveNodes();//删除现有的nodes
            xd2.Root.Element("Mrows").Add(els2);//把那个自己分析出来的node加进来。
           return xd2.ToString();
           
        }

       /// <summary>
       /// 排序有很多行，所以这个是获取某一排序关键Key，然后获取。
       /// </summary>
       /// <param name="TYPE"></param>
       /// <param name="KEY"></param>
       /// <param name="xd"></param>
       /// <returns></returns>
        private static IEnumerable<System.Xml.Linq.XElement> MoreRow(string TYPE, string KEY, System.Xml.Linq.XDocument xd)
        {
            //多条row
            IEnumerable<System.Xml.Linq.XElement> els2;
            if (TYPE == "Ct")
            {
                els2 = from c in xd.Root.Element("Mrows").Elements("row")
                       where c.Element("Ct").Value.Contains(KEY)
                       select c;
                var els2a = els2.ToArray();
                return els2a;
            }
            else
            {
                els2 = (from c in xd.Root.Element("Mrows").Elements("row")
                        where !c.Element("Ct").Value.Contains(KEY) && (from row in c.Element("Mrowwebs").Elements("web")
                                                                       where row.Element(TYPE).Value.Contains(KEY)
                                                                       select row).Count() > 0
                        select c);//5
                var els2a = els2.ToArray();
                for (int i = 0; i < els2a.Length; i++)//循环每条row
                {
                    IEnumerable<System.Xml.Linq.XElement> els21 = OneRow(els2a[i], TYPE, KEY);//得到web

                    els2a[i].Element("Mrowwebs").RemoveNodes();//删除掉webs，
                    els2a[i].Element("Mrowwebs").Add(els21);//把新的webs加入进来。

                }
                return els2a;
            }
            
        }

        /// <summary>
        /// 这里是获取，某一个row的web的。
        /// </summary>
        /// <param name="els2"></param>
        /// <param name="TYPE"></param>
        /// <param name="KEY"></param>
        /// <returns></returns>
        private static IEnumerable<System.Xml.Linq.XElement> OneRow(System.Xml.Linq.XElement els2, string TYPE, string KEY)
        {
            IEnumerable<System.Xml.Linq.XElement> els21 = null;

            var els211 = from row in els2.Element("Mrowwebs").Elements("web")
                         where row.Element(TYPE).Value.Contains(KEY)

                         select row;//根据row，获取webs，select语句。


            els21 = els211.ToArray();
            return els21;
        }

        /*************************************************

        Function: // searchXML

        Description: // 从XML文件中查找含有关键词的节点,组成json字符串后返回。

     Calls: // 被本函数调用的函数清单

     Called By: // 调用本函数的函数清单

     Table Accessed: // 被访问的表（此项仅对于牵扯到数据库操作的程序）

     Table Updated:  // 被修改的表（此项仅对于牵扯到数据库操作的程序）

     Input: // key为关键词

            // 用、取值说明及参数间关系。

     Output: // json字符串。

     Return: // 

     Others: // 其它说明

    //*************************************************/
    //    public static string searchXML(string key,string filepath)
    //    {
    //        XmlDocument doc = new XmlDocument();
    //        using (StreamReader sr = new StreamReader("filepath", Encoding.UTF32))
    //        {
    //            doc.Load(sr);
    //            XmlNodeList nodes = doc.SelectNodes("//web[@Name="+key+"]");
    //            foreach (XmlNode item in nodes)
    //            {
    //                string name = item.SelectSingleNode("//ns:Name").InnerText;
    //                string age = item.SelectSingleNode("//ns:Age").InnerText;
    //            }
    //            StringBuilder strBuilder = new StringBuilder();
    //            strBuilder.Append("{ 'page': {'Id':'searchPageID','Mtables':{'table':[{'Id':'0000000SEARCHWEBTABLE','Mrows':{'row':[{'Ct':'");
    //            strBuilder.Append(key);
    //            strBuilder.Append("','Id':'0000000000000CATE','Mrowwebs':{'web':[");
    //            if (reader.HasRows)
    //            {
    //                int len = 0;
    //                while (reader.Read())
    //                {
    //                    len = len + reader[1].ToString().TrimEnd().Replace("[^x00-xff]", "aa").Length * 8 + 5;
    //                    if (len > 600)//长度大于600时另外增加一行.
    //                    {
    //                        strBuilder.Remove(strBuilder.Length - 1, 1);//把循环-1-处的,去掉.
    //                        len = 0;
    //                        strBuilder.Append("]}},{'Ct':'");
    //                        strBuilder.Append(key);
    //                        strBuilder.Append("','Id':'0000000000000CATE','Mrowwebs':{'web':[");
    //                    }
    //                    strBuilder.Append("{");
    //                    strBuilder.Append("'ID':'" + reader[0] + "',");
    //                    strBuilder.Append("'Name':'" + reader[1] + "',");
    //                    strBuilder.Append("'Link':'" + reader[2] + "',");
    //                    strBuilder.Append("'Note':'" + reader[4] + "'");
    //                    strBuilder.Append("},");//-1-
    //                }
    //                strBuilder.Remove(strBuilder.Length - 1, 1);
    //            }
    //        }
    //    }

        public static string search(string key)
        {
            key = key.Trim().Replace("'","").Replace("=","");
            if (key == "")
            {
                return "";
            }
            //Data Source=HP-CQ57\\SQLEXPRESS;Initial Catalog=webCelloction;Integrated Security=True;Pooling=False
            SqlConnection conn = new SqlConnection("data source=127.0.0.1,1433;User ID=a0223133454;pwd=23144119;Initial Catalog=a0223133454");
            SqlCommand cmd = new SqlCommand("select * from webRank where name like '%" + key + "%'", conn);
            conn.Open();
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.Append("{ 'page': {'Id':'searchPageID','Mtables':{'table':[{'Id':'0000000SEARCHWEBTABLE','Mrows':{'row':[{'Ct':'");
            strBuilder.Append(key);
            strBuilder.Append("','Id':'0000000000000CATE','Mrowwebs':{'web':[");
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.HasRows)
            {
                int len = 0;
                while (reader.Read())
                {
                    len = len + reader[1].ToString().TrimEnd().Replace("[^x00-xff]","aa").Length * 8 + 5;
                    if (len > 600)//长度大于600时另外增加一行.
                    {
                        strBuilder.Remove(strBuilder.Length - 1, 1);//把循环-1-处的,去掉.
                        len = 0;
                        strBuilder.Append("]}},{'Ct':'");
                        strBuilder.Append(key);
                        strBuilder.Append("','Id':'0000000000000CATE','Mrowwebs':{'web':[");
                    }
                    strBuilder.Append("{");
                    strBuilder.Append("'ID':'" + reader[0] + "',");
                    strBuilder.Append("'Name':'" + reader[1] + "',");
                    strBuilder.Append("'Link':'" + reader[2] + "',");
                    strBuilder.Append("'Note':'" + reader[4] + "'");
                    strBuilder.Append("},");//-1-
                }
                strBuilder.Remove(strBuilder.Length - 1, 1);
            }
            else
            {
                strBuilder.Append("{");
                strBuilder.Append("'ID':'0000WEB',");
                strBuilder.Append("'Name':'there is no result.',");
                strBuilder.Append("'Link':'www.nochoose.com',");
                strBuilder.Append("'Note':'nochoose'");
                strBuilder.Append("}");
            }
            strBuilder.Append("]}}]}}]}}}");
            conn.Close();
            return strBuilder.ToString();
        }

        public static void gatherDataToDB(string _name,string _link,string _note)
        {
            try
            {
                if (!Regex.IsMatch(_link, @".*(\w+\.){1,}\w+"))
                    return;
                SqlConnection conn = new SqlConnection("data source=127.0.0.1,1433;User ID=a0223133454;pwd=23144119;Initial Catalog=a0223133454");
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                conn.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "webRank_Add_produce";
                SqlParameter pWebName = new SqlParameter();
                pWebName.ParameterName = "@name";
                pWebName.SqlDbType = SqlDbType.NChar;

                SqlParameter pWebLink = new SqlParameter();
                pWebLink.ParameterName = "@link";
                pWebLink.SqlDbType = SqlDbType.NVarChar;

                SqlParameter pWebRank = new SqlParameter();
                pWebRank.ParameterName = "@rank";
                pWebRank.SqlDbType = SqlDbType.SmallInt;

                SqlParameter pWebNote = new SqlParameter();
                pWebNote.ParameterName = "@note";
                pWebNote.SqlDbType = SqlDbType.NVarChar;

                pWebName.Value = _name;
                pWebLink.Value = _link;
                pWebRank.Value = 1;
                pWebNote.Value = _note;
                cmd.Parameters.Clear();
                cmd.Parameters.Add(pWebName);
                cmd.Parameters.Add(pWebLink);
                cmd.Parameters.Add(pWebRank);
                cmd.Parameters.Add(pWebNote);
                cmd.ExecuteNonQuery();

                conn.Close();
            }
            catch (Exception ex)
            {
                LOG.writer(ex.Message);
            }
        }
}
